package procsim;

import java.util.*;

public abstract class LogicalElement implements Element {
    protected Signal result;
    protected int res;
    protected ArrayList<Sig> list = new ArrayList<Sig>(10);
    protected boolean inverted = false;
    public LogicalElement add(Signal sig){
        list.add(sig);
        if(sig!=null) sig.addElement(this);
        return this;
    }
    public LogicalElement setResult(Signal sig){
        result=sig;
        return this;
    }
    @Override
    public Signal result() {
        return result;
    }
    public LogicalElement not(){
        inverted = Util.toggle(inverted);
        return this;
    }
    protected void invertIfNeeded(){ // pozivati posle tick-a
        if(result!=null && inverted) result.not();
    }

    protected boolean isInverted(){
        if(inverted) return true;
        else return false;
    }

    @Override
    public void updateSignal(Sig sig){
        ArrayList<Sig> newlist = new ArrayList<Sig>();
        boolean changed = false;
        Iterator iter = list.iterator();
        while(iter.hasNext()){
            Signal cur = ((Signal)iter.next());
            if(cur==sig){
                newlist.add(sig);
                changed = true;
            } else
                newlist.add(cur);
        }
        list = newlist;
        if(changed) tick();
    }
}
